package com.ass.wechat.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.ass.base.service.BaseServiceImpl;
import com.ass.common.generated.dao.WcAccesstokenMapper;
import com.ass.common.generated.dao.WcWechatmenuMapper;
import com.ass.common.generated.model.WcAccesstoken;
import com.ass.common.generated.model.WcAccesstokenExample;
import com.ass.common.generated.model.WcWechatmenu;
import com.ass.common.generated.model.WcWechatmenuExample;
import com.ass.common.utils.DateUtil;
import com.ass.common.utils.JsonUtil;
import com.ass.common.utils.StringUtil;
import com.ass.wechat.dto.MenuDTO;
import com.ass.wechat.dto.WeChatGeneratorParam;



@Service
public class MenuServiceImpl extends BaseServiceImpl  implements MenuService   {

	@Resource
	private WcWechatmenuMapper wcWechatmenuMapper;
	
	@Resource
	private WcAccesstokenMapper wcAccesstokenMapper;
	
	
	@Override
	public void setMenu() throws Exception {
		// 拿到菜单表List
        List<MenuDTO> menu = this.getMenuList();
        // 拼写json字符串
        String menuStr = this.spellPushMenu(menu);
        System.out.println(menuStr);
        
        //
        String accessToken = this.getWeChatGeneratorParam().getAccessToken();
        //post https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
		String url = this.getProp("weixin.getmenu.url") + "?access_token=" + accessToken;
		
		
		PostMethod pm = new PostMethod(url);
		pm.addRequestHeader("Content-Type","text/html;charset=UTF-8");
		pm.setRequestBody(menuStr);
		
		HttpClient httpClient = new HttpClient();
		httpClient.executeMethod(pm);
		//正确的响应 {"errcode":0,"errmsg":"ok"}
		String result = pm.getResponseBodyAsString();
		
		Map<String, Object> resultMap = (Map<String, Object>) JsonUtil.readValue(result, Map.class);
		if (0==(Integer)resultMap.get("errcode")){
			System.out.println("创建微信菜单成功");
		}else{
			System.out.println("创建微信菜单失败 errcode："+resultMap.get("errcode"));
		}
        
	}
	
	
	
	
	
	/**需要用到accessToken的时候就调用这个方法
	 * @return
	 * @throws Exception
	 */
	public WeChatGeneratorParam getWeChatGeneratorParam() throws Exception {
		WeChatGeneratorParam param = new WeChatGeneratorParam();
		// Token
		param.setToken(this.getProp("wechat.token"));
		// Appid
		param.setAppid(this.getProp("wechat.appId"));
		// AppSecret
		param.setAppSecret(this.getProp("wechat.appSecret"));
		param.setGrantType(this.getProp("wechat.granttype"));
		String accessToken = this.getAccessToken(param);
		param.setAccessToken(accessToken);
		return param;
	}
	
	
	//获得accessToken
	protected String getAccessToken(WeChatGeneratorParam wechatGeneralParam) throws Exception {
		//accessToken生效时间是7200秒
		//判断是否需要重新获得
		//accesstoken表中只有一条记录
		WcAccesstokenExample e = new WcAccesstokenExample();
		e.setOrderByClause(" id desc ");//取最新的
		List<WcAccesstoken> lst = wcAccesstokenMapper.selectByExample(null);
		String accessToken = "";
		if(lst.size() == 0 ){
			accessToken = "";
		}else{
			int nowtimestamp = DateUtil.getCurrentTimestamp();
			int old = lst.get(0).getTimestamp();
			int chazhi = nowtimestamp - old;
			if(chazhi < 7200){
				accessToken = StringUtil.getString(lst.get(0).getAccesstoken());
			}else{
				accessToken = "";//生效 超时
			}
		}
		if (StringUtils.isEmpty(accessToken)) {
			
			//get
			//https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
			String url = this.getProp("wechat.access_token.url")+"?grant_type="+wechatGeneralParam.getGrantType()
					+"&appid="+wechatGeneralParam.getAppid()+"&secret="+wechatGeneralParam.getAppSecret();
			System.out.println("调用微信获取accesstoken地址："+url);
			HttpClient httpClient = new HttpClient();
	        GetMethod procGet = new GetMethod(url);
	        httpClient.executeMethod(procGet);

	        // 读取内容
	        String result = procGet.getResponseBodyAsString();
	        System.out.println("调用微信获取accesstoken返回Json："+result);

			Map<String, String> m = (Map<String, String>) JsonUtil.readValue(result, Map.class);
			//正常情况 {"access_token":"ACCESS_TOKEN","expires_in":7200}
			//错误 实例 {"errcode":40013,"errmsg":"invalid appid"}
			if (StringUtils.isNotEmpty(m.get("errcode"))) {
				accessToken = "";
			} else {
				accessToken = m.get("access_token");
				//保存到数据库
				WcAccesstoken a = new WcAccesstoken();
				a.setAccesstoken(accessToken);
				a.setTimestamp(DateUtil.getCurrentTimestamp());
				wcAccesstokenMapper.insertSelective(a);

			}
		}
		return accessToken;
	}
	
	
	@Override
	public String spellPushMenu(List<MenuDTO> menu) {
		StringBuilder weixinMenuStr = new StringBuilder();
		weixinMenuStr.append("{\"button\": [");
		String sp = "";
		String subsp = "";
		for (MenuDTO menuDTO : menu) {
			if (null == menuDTO.getMenuDTOList() || menuDTO.getMenuDTOList().size() == 0) {
				if("click".equals(menuDTO.getMenuType())){
					weixinMenuStr.append(sp).append("{\"key\":\"").append(menuDTO.getMenuParam()).append("\",\"type\":\"").
					append(menuDTO.getMenuType()).append("\",\"name\":\"").append(menuDTO.getMenuName()).append("\"}");
				}else{
					weixinMenuStr.append(sp).append("{\"url\":\"").append(menuDTO.getMenuParam()).append("\",\"type\":\"").
					append(menuDTO.getMenuType()).append("\",\"name\":\"").append(menuDTO.getMenuName()).append("\"}");
				}
			} else {
				weixinMenuStr.append(sp).append("{\"name\":\"").append(menuDTO.getMenuName()).append("\",\"sub_button\":[");
				for (MenuDTO submenu : menuDTO.getMenuDTOList()) {
					if("click".equals(submenu.getMenuType())){
						weixinMenuStr.append(subsp).append("{\"key\":\"").append(submenu.getMenuParam()).append("\",\"type\":\"").
						append(submenu.getMenuType()).append("\",\"name\":\"").append(submenu.getMenuName()).append("\"}");
					}else{
						weixinMenuStr.append(subsp).append("{\"url\":\"").append(submenu.getMenuParam()).append("\",\"type\":\"").
						append(submenu.getMenuType()).append("\",\"name\":\"").append(submenu.getMenuName()).append("\"}");
					}
					subsp = ",";
				}
				subsp = "";
			}
			weixinMenuStr.append("]}");
			sp = ",";
		}
		weixinMenuStr.append("]}");
		return weixinMenuStr.toString();
	}
	
	
	
	
	
	
	
	
	
	
	
	@Override
	public List<MenuDTO> getMenuList() {
		//查询一级菜单
		WcWechatmenuExample example = new WcWechatmenuExample();
		WcWechatmenuExample example2 = new  WcWechatmenuExample();
		example.createCriteria().andPidEqualTo(0);
		example.setOrderByClause(" sidx asc ");
		List<WcWechatmenu> list = wcWechatmenuMapper.selectByExample(example);
		
		List<MenuDTO> menuList = new ArrayList<MenuDTO>();
		for(WcWechatmenu wcmenu:list){
			MenuDTO menuDTO = new MenuDTO();
			menuDTO.setMenuName(wcmenu.getName());
			menuDTO.setMenuParam(wcmenu.getParam());
			menuDTO.setMenuType(wcmenu.getType());
			//查询子菜单
			example2.clear();
			example2 = new WcWechatmenuExample();
			example2.createCriteria().andPidEqualTo(wcmenu.getId());
			example2.setOrderByClause(" sidx asc ");
			List<WcWechatmenu> sublist= wcWechatmenuMapper.selectByExample(example2);
			if (null != sublist && sublist.size() > 0) {
				List<MenuDTO> submenuList = new ArrayList<MenuDTO>();
				for(WcWechatmenu subMenu:sublist){
					MenuDTO submenuDTO = new MenuDTO();
					submenuDTO.setMenuName(subMenu.getName());
					submenuDTO.setMenuParam(subMenu.getParam());
					submenuDTO.setMenuType(subMenu.getType());
					submenuList.add(submenuDTO);
				}
				menuDTO.setMenuDTOList(submenuList);
			}
			menuList.add(menuDTO);
		}
		
		return menuList;
	}






public static void main(String[] args) {
	MenuServiceImpl m = new MenuServiceImpl();
	try {
		m.setMenu();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}





	
	
	
	
	
	
	
}
